package com.demo.boss.server.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.boss.common.constants.type.SysException;
import com.demo.boss.common.enums.PublicStatus;
import com.demo.boss.common.enums.SysCode;
import com.demo.boss.entity.UserAccount;
import com.demo.boss.entity.UserInfo;
import com.demo.boss.mapper.UserAccountMapper;
import com.demo.boss.mapper.UserInfoMapper;
import com.demo.boss.models.PageRequest;
import com.demo.boss.models.request.UserEditRequest;
import com.demo.boss.models.vo.UserInfoVo;
import com.demo.boss.server.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserAccountMapper userAccountMapper;
    @Override
    public IPage<UserInfo> queryPageList(PageRequest pageRequest) {
        // 构建查询条件（指定泛型为 UserInfo）
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time"); // 确保数据库中存在 create_time 字段

        // 执行分页查询
        IPage<UserInfo> pageResult = userInfoMapper.selectPage(Page.of(pageRequest.getPageNo(), pageRequest.getPageSize()), wrapper);
        return pageResult;
    }
    @Override
    public UserInfo queryByUserNo(String userNo) {
        return userInfoMapper.selectOne(new QueryWrapper<UserInfo>()
                .eq("user_no",userNo));
    }

    @Override
    public List<UserInfo> matchShopName(String shopName) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.select("user_no","shop_name")
                .like("shop_name",shopName)
                .orderByAsc("user_no");

        return  userInfoMapper.selectList(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registerOrEdit(UserEditRequest editRequest) {
        // 1、login_name 字段不能重复
        if (StrUtil.isNotBlank(editRequest.getUserNo())) {
            // 有就是修改
            UpdateWrapper<UserInfo> wrapper = new UpdateWrapper<>();
            wrapper.eq("user_no",editRequest.getUserNo())
                    .set("phone",editRequest.getPhone())
                    .set("login_name",editRequest.getLoginName())
                    .set("shop_name",editRequest.getShopName())
                    .set("shop_scope",editRequest.getShopScope())
                    .set("user_email",editRequest.getUserEmail());
            int result = userInfoMapper.update(wrapper);
            if (result == 0){
                throw new SysException(SysCode.DEFAULT_ERROR);
            }

        } else { // 没有就是 新增
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("login_name", editRequest.getLoginName());
            Long count = userInfoMapper.selectCount(wrapper); // 查询 该条件 的值有多条
            if (count > 0) {
                throw new SysException(SysCode.USER_LOGIN_NAME_EXISTS_ERROR);
            }
            // 新增商户
            UserInfo userInfo = new UserInfo();
            userInfo.setId(IdWorker.get32UUID());
            userInfo.setUserNo("8" + IdWorker.getId()); // IdWorker.getId 使用雪花算法生成 long 类型的唯一值
            userInfo.setLoginName(editRequest.getLoginName());
            userInfo.setAccountNo("9" + IdWorker.getId());
            userInfo.setPhone(editRequest.getPhone());
            userInfo.setPassword(IdWorker.get32UUID());
            userInfo.setPayPwd(IdWorker.get32UUID());
            userInfo.setShopName(editRequest.getShopName());
            userInfo.setShopScope(editRequest.getShopScope());
            userInfo.setUserEmail(editRequest.getUserEmail());
            // 插入时存储枚举名称
            log.info("插入的status值：{}", PublicStatus.ENABLE.name());
            userInfo.setStatus(PublicStatus.ENABLE.name());

            userInfo.setCreateTime(new Date());
            userInfo.setRemark("创建商户");
            userInfoMapper.insert(userInfo);
            // 新增商户账户
            UserAccount userAccount = new UserAccount();
            userAccount.setId(IdWorker.get32UUID());
            userAccount.setUserNo(userInfo.getUserNo());
            userAccount.setAccountNo(userInfo.getAccountNo());
            userAccount.setBalance(new BigDecimal("0"));
            userAccount.setTotalIncome(new BigDecimal("0"));
            userAccount.setTotalExpend(new BigDecimal("0"));
            userAccount.setStatus(PublicStatus.ENABLE.name());
            userAccount.setRemark("创建资金账号");
            userAccount.setEditTime(new Date());
            userAccountMapper.insert(userAccount);

        }
    }


}
